package cn.stylefeng.guns.schedule;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import cn.stylefeng.guns.base.utils.StringUtil;
import cn.stylefeng.guns.modular.common.service.CommonService;
import cn.stylefeng.guns.wechat.WeChatMsgSend;
import cn.stylefeng.guns.wechat.WeChatUrlData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.*;

import static cn.stylefeng.guns.base.consts.ConfigConstant.*;

@Component
@Slf4j
public class JSSCSchedule  implements CommandLineRunner {
    @Autowired
    private CommonService commonService;

    final static Integer ISSUE = 72881;
    final static Date DATE_INIT = DateUtil.parseDate("2022-12-12");

    static Map<String, Integer> CODE1 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE2 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE3 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE4 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE5 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE6 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE7 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE8 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE9 = Maps.newLinkedHashMap();
    static Map<String, Integer> CODE10 = Maps.newLinkedHashMap();

    static List<Map<String, Integer>> codeMaps = Arrays.asList(CODE1, CODE2, CODE3, CODE4, CODE5, CODE6, CODE7, CODE8, CODE9, CODE10);
    static Set<Long> ISSUE_SET = Sets.newHashSet();

    @Override
    public void run(String... args) throws Exception {
//        new Thread(() -> {
//            JSONArray datas = getData();
//            initYiLouData(datas);
//            while (true) {
//                Long issueNow = getIssue();
//                sleep(issueNow);
//            }
//        }).start();
    }

//    @SneakyThrows
//    public static void main(String[] args) {
//        JSSCSchedule schedule = new JSSCSchedule();
////        JSONArray datas = schedule.getData2("D:\\乱七八糟\\jssc.txt");
//        JSONArray datas = schedule.getData();
//        schedule.initYiLouData(datas);
//        while (true) {
//            Long issueNow = schedule.getIssue();
//            schedule.sleep(issueNow);
//        }
//    }

    public void sleep(Long issue) {
//        log.info("total:{},ss:{},issue:{},ISSUE:{}", total, ss, issue, ISSUE_SET);
        if (ISSUE_SET.add(issue)) {
            ThreadUtil.sleep(5000);
//            JSONArray datas2 = getData2("D:\\乱七八糟\\jssc2.txt");
            JSONArray datas2 = getData();
            List<Map<String, Integer>> codes = getYiLou(datas2);
            judge(codes, issue);
        } else {
            if (ISSUE_SET.size() > 1000) {
                ISSUE_SET.clear();
                ISSUE_SET.add(issue);
            }
            ThreadUtil.sleep(1000);
        }
    }

    public Long beginIssueOfToday() {
        long day = DateUtil.between(DATE_INIT, new Date(), DateUnit.DAY, true);
        return ISSUE + day * 1151;
    }

    public Long getIssue() {
        long issue = beginIssueOfToday();
        long now = SystemClock.now();
        long begin = DateUtil.beginOfDay(new Date()).getTime() + 33000;
        long time = (now - begin) / 1000;
        return (time - time % 75) / 75 + issue;
    }

    public JSONArray getData() {
        //             https://api.api168168.com/pks/getPksHistoryList.do?lotCode=10037
        String url2 = "https://api.api68.com/pks/queryToDayNumberLawOfStatistics.do?date=&lotCode=10037";
        JSONObject res = JSONObject.parseObject(HttpUtil.createGet(url2)
                .header(Header.USER_AGENT, AGENT)
                .header(Header.ACCEPT, ACCEPT)
                .execute().body());

        JSONArray datas = res.getJSONObject("result").getJSONArray("data");
        return datas;
    }

    public JSONArray getData2(String path) {
        JSONObject res = JSONObject.parseObject(FileUtil.readString(path, Charset.defaultCharset()));

        JSONArray datas = res.getJSONObject("result").getJSONArray("data");
        return datas;
    }

    public void initYiLouData(JSONArray datas) {
        List<Map<String, Integer>> maps = getYiLou(datas);
        for (int i = 0; i < maps.size(); i++) {
            codeMaps.get(i).putAll(maps.get(i));
            System.out.println(codeMaps.get(i));
        }
    }


    public List<Map<String, Integer>> getYiLou(JSONArray datas) {
        List<Map<String, Integer>> codeMaps = Lists.newArrayList();
        for (int i = 0; i < datas.size(); i++) {
            Map<String, Integer> map = Maps.newLinkedHashMap();
            codeMaps.add(map);
        }

        for (int i = 0; i < datas.size(); i++) {
            JSONObject data = datas.getJSONObject(i);
            JSONArray lists = data.getJSONArray("list");
            String code = data.getString("code");
            for (int j = 0; j < lists.size(); j++) {
                JSONObject list = lists.getJSONObject(j);
                Integer rank = Integer.valueOf(list.getInteger("rank"));
                int missing = Math.abs(Integer.valueOf(list.getInteger("missing")));
                codeMaps.get(rank - 1).put(code, missing);
            }
        }

        for (int i = 0; i < codeMaps.size(); i++) {
            Map<String, Integer> codeMap = codeMaps.get(i);
            StringUtil.sortMap(codeMap);
        }
        return codeMaps;
    }

    static Map<Integer, Integer> max = Maps.newHashMap();
    public void judge(List<Map<String, Integer>> codes, Long issue) {
        for (int i = 0; i < codes.size(); i++) {
            String old = StringUtil.getMap4Num(codeMaps.get(i), 1);
            String now = StringUtil.getMap4Num(codes.get(i), 1);
            if (!Objects.equals(now, old)) {
                log.info("{},位置:{},最大变化，旧:{},新:{}", issue, i + 1, old, now);
//                send(1000015, StrUtil.format("{},位置:{},最大变化，旧:{},新:{}", issue, i + 1, old, now));
                if (max.get(i) != null) {
                    String msg = StrUtil.format("{},位置:{},连续2次最大变化，旧:{},新:{}", issue, i + 1, old, now);
                    log.info(msg);
                    send(1000015, msg);
                }
                max.put(i, i);
            } else {
                max.remove(i);
            }
            codeMaps.set(i, codes.get(i));
        }
    }

    @SneakyThrows
    public void send(Integer appid, String warnMsg) {
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", warnMsg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }
}
